import os
from django.core.wsgi import get_wsgi_application

# 启动django
from tornado import ioloop
from tornado.httpclient import AsyncHTTPClient
import logging as log

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.INFO)

os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
get_wsgi_application()
import settings
import tornado.httpserver
import tornado.ioloop
import tornado.wsgi
from tornado.options import parse_command_line

from app_urls import urls

AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")


def ping_db():
    from app.models import Advertisement
    Advertisement.objects.first()


def run():
    # parse_command_line()
    address, port, env = settings.ADDRESS, settings.PORT, settings.ENV
    tornado_env = settings.TORNADO_ENV
    tornado_application = tornado.web.Application(urls, **tornado_env)
    tornado_server = tornado.httpserver.HTTPServer(tornado_application, xheaders=True, max_buffer_size=500000000)
    tornado_server.listen(port, address)
    print('huanxi_v2 server run on {}({}:{})'.format(env, address, port))
    tornado.ioloop.PeriodicCallback(ping_db, int(10 * 1000)).start()
    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    run()
